﻿using GGetTestService.MyDbContext;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;


namespace GGetTestService.Repository.UnitOfWork
{

    public class UnitOfWork : IUnitOfWork, IDisposable
    {
        private readonly SqlServerDbContext _dbContext;

        private readonly Dictionary<int, object> _repositoryContainer;
        public UnitOfWork(SqlServerDbContext dbContext)
        {
            _dbContext = dbContext;
            _repositoryContainer = new Dictionary<int, object>();
        }

        public IRepository<TEntity> GetRepository<TEntity>() where TEntity : class
        {
            var name = typeof(TEntity).FullName.GetHashCode();
            if (!_repositoryContainer.ContainsKey(name))
            {
                _repositoryContainer.Add(name, new EFRepository<TEntity, SqlServerDbContext>(_dbContext));
            }

            return _repositoryContainer[name] as IRepository<TEntity>;
        }

        public async Task<int> SaveChangesAsync()
        {
            int num;
            try
            {
                num = await _dbContext.SaveChangesAsync();
            }
            catch (DbUpdateException e)
            {
                Dispose();
                throw new Exception(e.InnerException == null ? e.Message : e.InnerException.Message);
            }
            return num;
        }

        #region Dispose
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool isDispose)
        {
            if (isDispose)
            {
                _dbContext.Dispose();
            }
        }

        #endregion
    }
}